package com.joint.base.util;

import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfig;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: xuzhou
 * Date: 2015/4/1
 * Time: 9:42
 */
public class ExportUtil {
    private static final Log logger = LogFactory.getLog(ExportUtil.class);

    private Template t;
    private Map<String, Object> dataMap;


    public ExportUtil(String templateName, FreeMarkerConfig freeMarkerConfig) throws IOException {
        try {
            t = freeMarkerConfig.getConfiguration().getTemplate("/ftl/" + templateName + ".ftl");
        } catch (IOException e) {
            logger.error("读取模板文件失败：", e);
        }
    }

    public ExportUtil setDataList(Map<String, Object> map) {
        this.dataMap = map;
        return this;
    }

    public void exportExcel(HttpServletResponse response, String fileName, HttpServletRequest request) {
        String userAgent = request.getHeader("USER-AGENT");
        try {
            if (StringUtils.contains(userAgent, "MSIE")) {// IE浏览器
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else if (StringUtils.contains(userAgent, "Mozilla")) {// google,火狐浏览器
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } else {
                fileName = URLEncoder.encode(fileName, "UTF8");// 其他浏览器
            }

        } catch (UnsupportedEncodingException e) {
            logger.error("不支持的编码：", e);
        }
        response.reset();
        response.setContentType("application/octet-stream; charset=utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xls");
        Writer out = null;
        try {
            out = response.getWriter();
            t.process(dataMap, out);
        } catch (IOException e) {
            logger.error("向客户端发送文件失败：", e);
        } catch (TemplateException e) {
            logger.error("往模板填充数据失败：", e);
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                // ...
            }
        }
    }
}
